package cn.yeamin.spring.boot.service;


import cn.yeamin.spring.boot.dao.GirlRepository;
import cn.yeamin.spring.boot.vo.Girl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2017/5/9.
 */
@Service
@CacheConfig(cacheNames = "girls")
public class GirlService {

    @Autowired
    private GirlRepository girlRepository;


    //为了可以更好的观察，缓存的存储，注入cacheManager。通过Debug查看缓存管理器是EhCacheCacheManage@5724
    @Autowired
    private CacheManager cacheManager;



    @Cacheable(key = "#p0")
    public Girl findById(Integer id){
        return girlRepository.findOne(id);
    }

    @Cacheable
    public List<Girl> findAll(){
        return girlRepository.findAll();
    }

    @CachePut(key = "#p0.id")
    public void save(Girl girl) {
        girlRepository.save(girl);
    }

    /**
     * @methodDesc: 方法描述:(更新时候要注意null字段)
     * @author: 李彤
     * @version: v1.0
     * @copyright:奕明(上海)影视传媒有限公司
     */
    @CachePut(key = "#p0.id")
    public void update(Girl girl) {
        Girl girl1 = this.findById(girl.getId());
        if (girl.getAge() != null) {
            girl1.setAge(girl.getAge());
        } else if (girl.getName() != null) {
            girl1.setName(girl.getName());
        } else if (girl.getCity() != null) {
            girl1.setCity(girl.getCity());
        }
        girlRepository.save(girl1);
    }

    @CacheEvict(cacheNames = "girls", allEntries = true)
    public void deleteById(Integer id) {
        girlRepository.delete(id);
    }


    /**
     * @methodDesc: 方法描述:(JPA查询的一种方法规则)
     * @author: 李彤
     * @version: v1.0
     * @copyright:奕明(上海)影视传媒有限公司
     */
    public Girl findByCity(String city){
        return girlRepository.findByCity(city);
    }


    public Girl queryAge(Integer age){
        return girlRepository.queryAge(age);
    }


}
